package com.chen.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("SESSION_USER") != null) {//已经登录
            return true;//可以进入controller
        }
        if (isAjax(request)) {
            Map<String, Object> result = new HashMap<>();
            result.put("login", false);
            result.put("message","请登录");
            ObjectMapper mapper=new ObjectMapper();
            String json=mapper.writeValueAsString(result);
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(json);
        }
            response.sendRedirect("/login.jsp");
            return false;//不能进入controller
    }

    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) || request.getParameter("ajax") != null;
    }
}
